# 读写一个 CSV 格式的文件。
# 默认情况下，csv 库可识别Microsoft Excel 所使用的CSV 编码规则.
# 如果你正在读取CSV 数据并将它们转换为命名元组，需要注意对列名进行合法性认证。
# csv 产生的数据都是字符串类型的，它不会做任何其他类型的转换。如果你需要做这样的类型转换，你必须自己手动去实现。

import csv
from collections import namedtuple

with open('stocks.csv') as f:
    f_csv = csv.reader(f)
    headers = next(f_csv)
    print(headers)
    for row in f_csv:
        print(row)
print()

# 按名称访问
with open('stocks.csv') as f:
    f_csv = csv.reader(f)
    headers = next(f_csv)
    Row = namedtuple('Row', headers)
    for r in f_csv:
        row = Row(*r)
        # process row

with open('stocks.csv') as f:
    f_csv = csv.DictReader(f)
    for row in f_csv:
        print(row)

# 写入数据
# headers = ['Symbol', 'Price', 'Date', 'Time', 'Change', 'Volume']
# rows = [("AA", 39.48, "6/11/2007", "9:36am", -0.18, 181800),
#         ("AIG", 71.38, "6/11/2007", "9:36am", -0.15, 195500),
#         ("AXP", 62.58, "6/11/2007", "9:36am", -0.46, 935000),
#         ("BA", 98.31, "6/11/2007", "9:36am", +0.12, 104800),
#         ("C", 53.08, "6/11/2007", "9:36am", -0.25, 360900),
#         ("CAT", 78.29, "6/11/2007", "9:36am", -0.23, 225400)
#         ]
# with open('stocks.csv', 'w') as f:
#     f_csv = csv.writer(f)
#     f_csv.writerow(headers)
#     f_csv.writerows(rows)
#
# rows_dict = [{'Symbol': symbol, 'Price': price, 'Date': date, 'Time': time, 'Change': change, 'Volume': volume}
#              for symbol, price, date, time, change, volume in rows]
# with open('stocks_dict.csv', 'w') as f:
#     f_csv = csv.DictWriter(f, headers)
#     f_csv.writeheader()
#     f_csv.writerows(rows_dict)
